# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import db
import sys
from datetime import date
import query, main

class AddPlanWindow (QtGui.QDialog):
    def __init__ (self,AppManObj, parent = None):
        self.app_man_obj = AppManObj
        QtGui.QDialog.__init__(self, parent)
        #setting the default values:
        self.default = {
            'min_price' : '0',
            'max_price' : '1',
            'description' : ''
            }
        self.parent = parent
        # The first row of the add Idea window
        # start time - QDate + label, End Time + label- q date,
        self.group_dates = QtGui.QGroupBox("Activity due:")
        self.days = self.get_time_interval()
        self.start_date = QtGui.QDateEdit(self.days[0], self.group_dates)
        self.end_date = QtGui.QDateEdit(self.days[1], self.group_dates)
        self.start_date_label = QtGui.QLabel("Start date")
        self.end_date_label = QtGui.QLabel("End date")
        self.date_box = QtGui.QGridLayout()
        self.date_box.addWidget(self.start_date_label, 0, 0)
        self.date_box.addWidget(self.start_date, 1, 0)
        self.date_box.addWidget(self.end_date_label,0, 1)
        self.date_box.addWidget(self.end_date, 1, 1)
        self.group_dates.setLayout(self.date_box)

        #setting ammount row

        self.group_amount = QtGui.QGroupBox("With price in range:")
        self.min_price = QtGui.QLineEdit(self.default['min_price'], self.group_amount)
        self.max_price = QtGui.QLineEdit(self.default['max_price'], self.group_amount)
        self.min_price_label = QtGui.QLabel("Minimum price", self.group_amount)
        self.max_price_label = QtGui.QLabel("Maximum price", self.group_amount)
        self.price_warning_label = QtGui.QLabel("", self.group_amount)
        self.price_box = QtGui.QGridLayout(self.group_amount)
        self.price_box.addWidget(self.price_warning_label, 0, 0)
        self.price_box.addWidget(self.min_price_label, 1, 0)
        self.price_box.addWidget(self.min_price, 2, 0)
        self.price_box.addWidget(self.max_price_label, 1, 1)
        self.price_box.addWidget(self.max_price, 2, 1)
        #description setting
        self.group_description = QtGui.QGroupBox("Please enter a 30 characters long or even less description here:", self)
        self.description = QtGui.QTextEdit(self.group_description)
        self.description_warning_label = QtGui.QLabel("", self.group_description)
        self.description_box = QtGui.QGridLayout(self.group_description)
        self.description_box.addWidget(self.description_warning_label, 0, 0)
        self.description_box.addWidget(self.description, 1, 0)
        #self.description_box.addWidget(self.description_warning_label, 1, 1)
        self.setWindowModality(QtCore.Qt.WindowModal)
        self.group_description.setLayout(self.description_box)
        # set up the control buttons
        self.group_buttons = QtGui.QGroupBox(self)
        self.btnOk = QtGui.QPushButton("Ok", self.group_buttons)
        self.btnClear = QtGui.QPushButton('Clear', self.group_buttons)
        self.btnCancel = QtGui.QPushButton("Cancel")
        self.buttons_box = QtGui.QHBoxLayout(self.group_buttons)
        self.buttons_box.addWidget(self.btnCancel)
        self.buttons_box.addWidget(self.btnClear)
        self.buttons_box.addWidget(self.btnOk)
        self.group_buttons.setLayout(self.buttons_box)
        #composition
        self.grid = QtGui.QGridLayout()
        self.grid.addWidget(self.group_dates, 0, 0)
        self.grid.addWidget(self.group_amount, 1, 0)
        self.grid.addWidget(self.group_description, 2, 0)
        self.grid.addWidget(self.group_buttons, 3, 0)
        self.setLayout(self.grid)

        self.price_warning_label.setVisible(False)
        self.description_warning_label.setVisible(False)
        self.connect(self.btnOk, QtCore.SIGNAL('clicked()'), self.check_data)
        self.connect(self.btnCancel, QtCore.SIGNAL('clicked()'), self.close_window)
        self.connect(self.btnClear, QtCore.SIGNAL('clicked()'), self.clear_data)


    def check_data (self):
        text = self.description.toPlainText()
        price = []
        price_numeric_passed = True
        price_relation_passed = True
        description_len_passed = True
        price.append(self.min_price.text())
        price.append(self.max_price.text())

        for i in range(0, 2):
            for j in price[i]:
                if j not in [
                    '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'
                    ]:
                    self.price_warning_label.setText("*Price can be only an integer number")
                    if self.price_warning_label.isVisible() == False:
                        self.price_warning_label.setVisible(True)
                    price_numeric_passed = False
                    break
        if price_numeric_passed == True:
            if int(price[0]) >= int(price[1]):
                self.price_warning_label.setText("*Minimum price must be smaller than Maximum")
                if self.price_warning_label.isVisible() == False:
                    self.price_warning_label.setVisible(True)
                price_relation_passed = False
            #elif int(price[1]) > self.parent.plans_space_left:
                #self.price_warning_label.setText(
                    #"*The Max price is bigger than money\nleft this month"
                    #)
                #if self.price_warning_label.isVisible() == False:
                    #self.price_warning_label.setVisible(True)
                #price_relation_passed = False
        if str(text) == self.default['description']:
            self.description_warning_label.setText("*Please enter description")
            if self.description_warning_label.isVisible() == False:
                self.description_warning_label.setVisible(True)
            description_len_passed = False
        elif len(text) > 30:
            if self.description_warning_label.isVisible() == False:
                self.description_warning_label.setVisible(True)
            self.description_warning_label.setText(
                "*Description cannot be longer than 30 characters"
                )
            description_len_passed = False

        if (
            description_len_passed and
            price_numeric_passed and
            price_relation_passed
            ):
            if self.description_warning_label.isVisible() == True:
                self.description_warning_label.setVisible(False)
            if self.price_warning_label.isVisible() == True:
                self.price_warning_label.setVisible(False)
            self.save_data()

    def save_data (self):
        print "starting data saving"
        values = []
        if self.app_man_obj.db_session.verbose_commander(
            query.update_actions(self.app_man_obj.db_session.username)
            ):
            self.app_man_obj.db_session.void_commander(
                query.extract_from_actions(self.app_man_obj.db_session.username)
                )
        else:
            QtGui.qApp.quit()
        last_event = self.app_man_obj.db_session.db_cursor.fetchall()
        values = [
            last_event[0]['event_id'],
            str(self.min_price.text()),
            str(self.max_price.text()),
            self.start_date.date().toPyDate(),
            self.end_date.date().toPyDate(),
            self.description.toPlainText(),
            ]
        self.app_man_obj.db_session.void_commander(
            query.add_idea(values)
            )
        #print last_event
        self.app_man_obj.db_session.db_cursor.connection.commit()
        self.clear_data()
        self.parent.update_planning()

    def get_time_interval (self):
        today = date.today()
        if today.month == 12:
            next_month = 1
        else:
            next_month = today.month + 1
        return [date(today.year, today.month, 1), date(today.year, next_month, 1)]

    def clear_data (self):
        date = self.get_time_interval()
        self.start_date.setDate(date[0])
        self.end_date.setDate(date[1])
        self.min_price.setText(self.default['min_price'])
        self.max_price.setText(self.default['max_price'])
        self.description.setText(self.default['description'])
        self.price_warning_label.setVisible(False)
        self.description_warning_label.setVisible(False)

    def close_window(self):
        self.close()

class PlanUpdateWindow(AddPlanWindow):

    def __init__(self, AppManObj, parent_dic, parent = None):
        AddPlanWindow.__init__(self, parent)
        self.parent = parent
        self.parent_dic = parent_dic
        self.app_man_obj = AppManObj
        self.default = {
            'min_price' : '0',
            'max_price' : '1',
            'description' : '',
            'inherited_max_price' : str(parent_dic['price_high']),
            'inherited_min_price' : str(parent_dic['price_low']),
            'inherited_description' : str(parent_dic['description']),
            'inherited_start_date' : parent_dic['start_date'],
            'inherited_finish_date' : parent_dic['finish_date'],
            'parent_id' : parent_dic['event'],
            'link' : "No link"
            }

        #self.btnDelete.setVisible(False)
        self.start_date.setDate(self.default['inherited_start_date'])
        self.end_date.setDate(self.default['inherited_finish_date'])
        self.min_price.setText(self.default['inherited_min_price'])
        self.max_price.setText(self.default['inherited_max_price'])
        self.description.setText(self.default['inherited_description'])
        self.btnDelete = QtGui.QPushButton('Delete', self.group_buttons)
        self.btnLog = QtGui.QPushButton('Log money', self.group_buttons)
        self.buttons_box.addWidget(self.btnDelete)
        self.buttons_box.addWidget(self.btnLog)

        self.connect(self.btnLog, QtCore.SIGNAL("clicked()"), self.log_window)
        self.connect(self.btnDelete, QtCore.SIGNAL("clicked()"), self.delete_plan)

    def delete_plan(self):
        if (self.app_man_obj.db_session.verbose_commander(
                query.planning_state_change(0, self.parent_dic['event']))
                ):
            self.parent.update_planning()
            self.app_man_obj.db_session.db_cursor.connection.commit()
            self.close()


    def log_window (self):
        defs = {
            'amount' : int(self.default['inherited_max_price']),
            'description' : self.default['inherited_description'],
            'url' : self.default['link'],
            'flag_value' : True,
            'event' : self.default['parent_id'],
            'date' : date.today()
            }
        self.app_man_obj.show_commit_planning(defs)
        self.close()


    def save_data (self):
        #print "starting data saving"
        values = []
        if self.app_man_obj.db_session.verbose_commander(
                query.update_actions(self.app_man_obj.db_session.username, self.default['parent_id'])
                ):
            self.app_man_obj.db_session.void_commander(
                query.extract_from_actions(self.app_man_obj.db_session.username)
                )
        else:
            QtGui.qApp.quit()
        last_event = self.app_man_obj.db_session.db_cursor.fetchall()
        #print "last_event ", last_event
        values = [
            last_event[0]['event_id'],
            str(self.min_price.text()),
            str(self.max_price.text()),
            self.start_date.date().toPyDate(),
            self.end_date.date().toPyDate(),
            self.description.toPlainText(),
            ]
        self.app_man_obj.db_session.void_commander(
            query.add_idea(values)
            )
        ##print last_event
        self.app_man_obj.db_session.void_commander(
            query.remove_plan(self.default['parent_id'])
            )
        self.app_man_obj.db_session.db_cursor.connection.commit()
        self.parent.update_planning()
        self.close()

class CommitPlanningWindow(main.UpdateCommitWindow):

    def __init__(self, AppManObj, parent_dic, parent= None):
        dictionary =parent_dic
        main.UpdateCommitWindow.__init__(self, AppManObj, dictionary, parent)
        #self.parent_dic = parent_dic
        self.btnDelete.setVisible(False)

    def save_data (self):
        #def save_data (self):
        ##print "entered save updated commit"
        values = []
        self.app_man_obj.db_session.void_commander(
            query.update_actions(self.app_man_obj.db_session.username, self.default['parent_id'])
            )
        self.app_man_obj.db_session.void_commander(
            query.extract_from_actions(self.app_man_obj.db_session.username)
            )
        last_event = self.app_man_obj.db_session.db_cursor.fetchall()
        ##print last_event
        values = [
            last_event[0]['event_id'],
            str(self.amount_edit.text()),
            self.date.date().toPyDate(),
            self.rbtnSpent.isChecked(),
            str(self.text_edit.toPlainText()),
            str(self.link_edit.text())
            ]
        ##print values
        ##print "date is: %s" % self.date.date().toPyDate()
        if self.app_man_obj.db_session.verbose_commander(
            query.commit(values)
            ):
            self.app_man_obj.db_session.void_commander(
                query.planning_state_change(2, self.parent_dic['event'])
                )
        self.app_man_obj.db_session.db_cursor.connection.commit()
        self.parent.update_planning()
        self.close()






